﻿<template>
  <div>
    <div class="map-container1">

      <!-- 地图容器 -->
      <div id="container" class="container1">
        <el-button type="primary" style="z-index: 1000;position: absolute" size="small" @click="yc">隐藏</el-button>
        <div class="search-container1" v-if="yincang">
          <div>
            <span>搜索：</span>
            <el-autocomplete
                v-model="keywords"
                style="width: 300px"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入内容"
                @select="handleSelect"
            ></el-autocomplete>

          </div>
          <!-- 起点输入框 -->
          <div style="margin-top: 10px">
            <span>起点：</span>
            <el-autocomplete
                v-model="startKeywords"
                style="width: 300px"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入起点"
                @select="handleStartSelect"
            ></el-autocomplete>
          </div>
          <!-- 终点输入框 -->
          <div style="margin-top: 10px">
            <span>终点：</span>
            <el-autocomplete
                v-model="endKeywords"
                style="width: 300px"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入终点"
                @select="handleEndSelect"
            ></el-autocomplete>
          </div>
          <!-- 查询按钮 -->
          <div style="margin-top: 10px">
            <el-button type="primary" @click="searchRoute">查询路线</el-button>
            <el-button type="primary" @click="searchNearbyFood">周边美食</el-button>
            <el-button type="primary" @click="searchNearbyFood1">周边景点</el-button>
            <el-button style="margin-left: 10px" type="danger" size="small" @click="reset">清空</el-button>
          </div>
          <div class="history">
            <h3>历史记录</h3>
            <h4>搜索:</h4>
            <ul>
              <li v-for="item in savedInfo" :key="item.id">
                {{ item.searchKeyword }}{{item.searchTime}}
              </li>
            </ul>
            <h4>终点:</h4>
            <el-button type="danger" @click="clearAllHistory">清除所有历史记录</el-button>
          </div>
          <!-- 路线详情 -->
          <div v-if="routeDetails" style="margin-top: 20px" class="route-details">
            <h3>路线详情</h3>
            <p>总距离：{{ routeDetails.distance }} 米</p>
            <p>总时间：{{ routeDetails.duration }} 分钟</p>
            <ul>
              <li v-for="(step, index) in routeDetails.steps" :key="index">
                <strong>第 {{ index + 1 }} 步：</strong>
                <p>{{ step.instruction }}</p>
                <p>距离：{{ step.distance }} 米</p>
                <p>时间：{{ step.duration }} 分钟</p>
                <p>道路：{{ step.road }}</p>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import axios from "axios";

window._AMapSecurityConfig = {
  securityJsCode: "aa7b6be2ffc49558cd2860ee6ec498c6",
};

export default {
  name: "HomeView",
  data() {
    return {
      map: null,
      // 标记点
      marker: null,
      // 地址逆解析
      geoCoder: null,
      // 搜索提示
      AutoComplete: null,
      //缩放控件
      ToolBar: null,
      //地图放大镜
      HawkEye: null,
      //比例尺
      Scale: null,
      //图层切换
      MapType: null,
      Geolocation: null,
      // 搜索关键字
      keywords: "",
      form: {
        lng: 116.157102,
        lat: 40.134066,
        address: '',
      },
      driving: null,
      startKeywords: "",
      endKeywords: "",
      startLocation: null,
      endLocation: null,
      routeDetails: null,
      // 搜索节流阀
      loading: false,
      options: [],
      foodMarkers: [],
      yincang: true,
      showHistory: false,
      savedInfo: {},
    };
  },
  created() {
    // this.selectall();
    this.initMap();
  },
  methods: {
    // yc() {
    //   if (this.yincang) {
    //     this.yincang = false
    //   } else {
    //     this.yincang = true
    //   }
    // },
    reset() {
      this.keywords = '';
      this.startKeywords = '';
      this.endKeywords = '';
      this.startLocation = null;
      this.endLocation = null;
      this.routeDetails = null;
      this.form = {
        lng: 116.157102,
        lat: 40.134066,
        address: '',
      };
      this.removeMarker();
      this.setMapMarker();
    },
    // clearAllHistory() {
    //   // 清除搜索历史记录，假设用户ID为固定值"user123"
    //   axios.delete('/search-history/clear?user_id=user123').then((response) => {
    //     console.log('搜索历史记录清除成功');
    //     this.searchHistory = [];
    //   }).catch((error) => {
    //     console.error('搜索历史记录清除失败：', error);
    //   });
    //
    //   // 清除终点历史记录，假设用户ID为固定值"user123"
    //   axios.delete('/end-history/clear?user_id=user123').then((response) => {
    //     console.log('终点历史记录清除成功');
    //     this.endHistory = [];
    //   }).catch((error) => {
    //     console.error('终点历史记录清除失败：', error);
    //   });
    // },
    initMap() {
      AMapLoader.load({
        key: "256ac6d4d7e01673de06f2cb06cf6ab4",
        version: "2.0",
        plugins: ["AMap.Geocoder", "AMap.AutoComplete", "AMap.ToolBar", "AMap.HawkEye", "AMap.Driving", "AMap.Scale", "AMap.MapType", "AMap.Geolocation"],
      }).then((AMap) => {
        this.map = new AMap.Map("container", {
          viewMode: "3D",
          zoom: 12,
          center: [this.form.lng, this.form.lat],
        });
        this.geoCoder = new AMap.Geocoder({
          city: "010", //城市设为北京，默认：“全国”
          radius: 1000, //范围，默认：500
        });
        this.AutoComplete = new AMap.AutoComplete({city: "全国"});
        this.ToolBar = new AMap.ToolBar({
          position: {
            bottom: '210px',
            right: '35px'
          }
        });
        // this.HawkEye = new AMap.HawkEye({
        //   position: {
        //     bottom: '110px',
        //     left: '35px'
        //   }
        // });
        // this.Scale = new AMap.Scale({
        //   position: {
        //     top: '650px',
        //     right: '35px',
        //   }
        // });
        // this.MapType = new AMap.MapType({
        //   defaultType: 'vec'
        // });
        // this.Geolocation = new AMap.Geolocation({
        //   enableHighAccuracy: true, // 是否使用高精度定位，默认:true
        //   timeout: 10000, // 超过10秒后停止定位，默认：无穷大
        //   maximumAge: 0, // 定位结果缓存0毫秒，默认：0
        //   convert: true, // 自动偏移坐标，偏移后的坐标为高德坐标，默认：true
        //   showButton: true, // 显示定位按钮，默认：true
        //   buttonPosition: 'LB', // 定位按钮停靠位置，默认：'LB'，左下角
        //   buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        //   showMarker: true, // 定位成功后在定位点显示marker，默认：true
        //   showCircle: true, // 定位成功后用圆圈表示定位精度范围，默认：true
        //   panToLocation: true, // 定位成功后将定位到的位置作为地图中心点，默认：true
        //   zoomToAccuracy: true // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        // });
        // this.map.addControl(this.MapType);
        // this.map.addControl(this.ToolBar);
        // this.map.addControl(this.HawkEye);
        // this.map.addControl(this.Scale);
        // this.map.addControl(this.Geolocation);
        // this.removeMarker();
        // this.setMapMarker();
        // this.map.on("click", (e) => {
        //   this.form.lng = e.lnglat.lng;
        //   this.form.lat = e.lnglat.lat;
        //   this.removeMarker();
        //   this.setMapMarker();
        // });
        // this.driving = new AMap.Driving({
        //   map: this.map, // 直接在这里设置地图实例
        //   showTraffic: true,
        //   policy: AMap.DrivingPolicy.LEAST_TIME,
        // });
      }).catch((err) => {
        console.error(err);
      });
    },


    setMapMarker() {
      this.map.setFitView();
      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.form.lng, this.form.lat],
      });
      this.toGeoCoder();
      this.map.setFitView();
      this.map.add(this.marker);
    },
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
      }
    },
    toGeoCoder() {
      let lnglat = [this.form.lng, this.form.lat];
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === "complete") {
          this.form.address = result.regeocode.formattedAddress;
        } else {
          this.form.address = '';
        }
      });
    },
    querySearchAsync(queryString, cb) {
      if (queryString) {
        AMap.plugin(["AMap.Autocomplete"], () => {
          const autoOptions = {
            city: "全国",
            input: queryString,
          };
          const autoComplete = new AMap.Autocomplete(autoOptions);
          autoComplete.search(queryString, (status, result) => {
            if (status === "complete" && result.tips) {
              this.options = result.tips.map((tip) => ({
                value: tip.name,
                location: tip.location,
              }));
            } else {
              this.options = [];
            }
            cb(this.options);
          });
        });
      } else {
        this.options = [];
        cb(this.options);
      }
    },
    handleSelect(val) {
      if (!val) {
        return;
      }
      console.log(val)
      this.form = {
        lng: val.location.lng,
        lat: val.location.lat,
      };
      this.removeMarker();
      this.setMapMarker();
      var searchHistory = {userId: "1", searchKeyword: val.value};
      this.axios.post(this.axios.URL1 + `map/search-history/save`, searchHistory).then(res => {
        console.log(res.data.data);
      })
    },
    handleStartSelect(item) {
      this.keywords = item.value;
      this.startLocation = item.location;
    },
    handleEndSelect(item) {
      this.endLocation = item.location;
      var endSearchHistory = {userId: "1", endpointKeyword: item.value};
      this.axios.post(this.axios.URL1 + `map/end-history/save`, endSearchHistory).then(res => {
        console.log(res.data.data);
      })
    },
    getCurrentPosition() {
      this.Geolocation.getCurrentPosition((status, result) => {
        if (status === 'complete') {
          this.startLocation = result.position;
          this.startKeywords = result.formattedAddress;
        } else {
          alert('获取当前位置失败');
        }
      });
    },
    searchRoute() {
      if (!this.startLocation) {
        this.getCurrentPosition();
      }
      if (!this.endLocation) {
        alert("请先选择终点");
        return;
      }

      this.driving.search(
          this.startLocation,
          this.endLocation,
          (status, result) => {
            if (status === "complete") {
              this.routeDetails = this.parseRouteDetails(result.routes[0]);
              console.log("绘制驾车路线完成");
            } else {
              alert("获取驾车数据失败！");
            }
          }
      );
    },
    parseRouteDetails(route) {
      const steps = route.steps.map((step) => ({
        instruction: step.instruction,
        distance: step.path.length * 10, // 近似距离
        duration: step.time / 60, // 时间转换为分钟
        road: step.road,
      }));

      return {
        distance: route.distance,
        duration: route.time / 60, // 总时间转换为分钟
        steps: steps,
      };
    },
    searchNearbyFood() {
      const center = this.map.getCenter();
      const lnglat = [center.lng, center.lat].join(',');

      AMap.plugin('AMap.PlaceSearch', () => {
        const placeSearch = new AMap.PlaceSearch({
          pageSize: 20,
          pageIndex: 1,
          city: '全国',
          extensions: 'all',
          output: 'json'
        });

        placeSearch.searchNearBy('美食', lnglat, 1000, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            this.displayFoodMarkers(result.poiList.pois);
          } else {
            console.error('搜索失败:', result);
          }
        });
      });
    },
    displayFoodMarkers(pois) {
      this.clearMarkers(); // 清除之前的标记

      pois.forEach(po => {
        const marker = new AMap.Marker({
          position: new AMap.LngLat(po.location.lng, po.location.lat),
          title: po.name,
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png' // 可以自定义图标
        });

        marker.setMap(this.map);
        this.foodMarkers.push(marker);
      });
    },
    clearMarkers() {
      this.foodMarkers.forEach(marker => {
        marker.setMap(null);
      });
      this.foodMarkers = [];
    },
    searchNearbyFood1() {
      const center = this.map.getCenter();
      const lnglat = [center.lng, center.lat].join(',');

      AMap.plugin('AMap.PlaceSearch', () => {
        const placeSearch = new AMap.PlaceSearch({
          pageSize: 20,
          pageIndex: 1,
          city: '全国',
          extensions: 'all',
          output: 'json'
        });

        placeSearch.searchNearBy('景点', lnglat, 1000, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            this.displayFoodMarkers1(result.poiList.pois);
          } else {
            console.error('搜索失败:', result);
          }
        });
      });
    },
    displayFoodMarkers1(pois) {
      this.clearMarkers1(); // 清除之前的标记

      pois.forEach(po => {
        const marker = new AMap.Marker({
          position: new AMap.LngLat(po.location.lng, po.location.lat),
          title: po.name,
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png' // 可以自定义图标
        });

        marker.setMap(this.map);
        this.foodMarkers.push(marker);
      });
    },
    clearMarkers1() {
      this.foodMarkers.forEach(marker => {
        marker.setMap(null);
      });
      this.foodMarkers = [];
    },
    toggleSavedInfo() {
      this.showSavedInfo = !this.showSavedInfo;
    },
    selectall() {
      this.axios.get(this.axios.URL1 + 'map/search-history/findall').then(res => {
        this.savedInfo = res.data;
        console.log(res.data)
      })
    },
  },

};
</script>

<style>
.container1 {
  width: 100%;
  height: 100vh;
  //left: 50px;
}

.search-container1 {
  position: absolute;
  top: 20px;
  left: 100px;
  background-color: white;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1000; /* 确保搜索组件在地图之上 */
  width: 450px;
}

.history {
  position: absolute;
  top: 20px;
  left: 1500px;
  background-color: white;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1000; /* 确保搜索组件在地图之上 */
  width: 350px;
}

.route-details {
  margin-top: 20px;
  height: 300px; /* 设置固定高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
  border: 1px solid #ccc; /* 可选：添加边框 */
  padding: 10px;
  background-color: #f9f9f9; /* 可选：背景颜色 */
}

.map-container1 {
  //max-width: 1280px;
  height: 720px;
  width: 2100px;
  //max-width: 1280px;
}
</style>
